package org.xgeometrywar;

import java.util.Random;

import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;

public class Engine extends Device implements Runnable {
	private MIDlet midlet;
	private Thread t;
	public final static int FRAME_DURATION = 80;

	private long startTime , endTime;
	
	private int mode;
	private final Random r;
	
	private int x , y , width ,height;
	public Engine(MIDlet midlet) {
		this.midlet = midlet;

		setFullScreenMode(true);

		fullScreenWidth = getWidth();
		fullScreenHeight = getHeight();
		
		halfFullScreenWidth = fullScreenWidth >> 1;
		halfFullScreenHeight = fullScreenHeight >> 1;
		
		r = new Random();
		
		width = 50;
		height = 50;
		
		x = (fullScreenWidth - width)>> 1;
		y = (fullScreenHeight - height) >> 1;
		
		t = new Thread(this);
		t.start();
	}

	public void run() {
		while (t != null) {
			long startTime = System.currentTimeMillis();

			tick();
			
			doRepaint();

			long duration = System.currentTimeMillis() - startTime;
			if (duration < FRAME_DURATION) {
				try {
					Thread.sleep(FRAME_DURATION - duration);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		midlet.notifyDestroyed();
	}

	private void tick() {
		if(keyPressed != KEY_NONE){
			if(keyPressedTime != 0){
				long keyPressInterval = System.currentTimeMillis() - keyPressedTime;
				if(keyPressInterval > FRAME_DURATION){
					repeatedKey = keyPressed;
				}				
			}
		}
		
//		if(repeatedKey != 0){
//			if (repeatedKey == KEY_LEFT) {
//				x -= 1;
//			}
//			
//			if (repeatedKey == KEY_RIGHT) {
//				x += 1;
//			}
//
//			if (repeatedKey == KEY_UP) {
//				y -= 1;
//			}
//
//			if (repeatedKey == KEY_DOWN) {
//				y += 1;
//			}
//		}
		
		if (isKeyPressed(KEY_LEFT)) {
			x -= 1;
		}
		
		if (isKeyPressed(KEY_RIGHT)) {
			x += 1;
		}

		if (isKeyPressed(KEY_UP)) {
			y -= 1;
		}

		if (isKeyPressed(KEY_DOWN)) {
			y += 1;
		}

		if (isKeyPressed(KEY_FIRE)) {
		}

		if (isKeyPressed(KEY_POUND)) {
		}
		
		if (isKeyPressed(KEY_STAR)) {
		}
		
		if (isKeyPressed(KEY_0)) {
			t = null;
		}
	}

	private void doRepaint() {
		repaint();
		serviceRepaints();
	}
	
	protected void paint(Graphics g) {
		super.paint(g);

		g.setColor(COLOR_WHITE);
		g.fillRect(0, 0, fullScreenWidth, fullScreenHeight);
		
		final int color = (r.nextInt(255) << 16) | (r.nextInt(255) << 8) | (r.nextInt(255));
		g.setColor(color);
		g.fillRect(x, y, width, height);
	}
}
